package com.qf.config;

import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

//开启security支持
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public PasswordEncoder passwordEncoder(){
//        return NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //关闭跨站伪造验证
        http.csrf().disable();

        //哪些资源需要登录
        http.authorizeRequests()
                //所有stu/**请求，都要求登录认证(更精确的路径应该配置在前面)
                .antMatchers("/stu/**","/pro/**").authenticated()
                //所有/**请求，都允许访问(范围更大的路径应该配置在后面)
                .antMatchers("/**").permitAll();

        //配置访问资源需要的权限
        http.authorizeRequests()
               .antMatchers("/stu/**").hasRole("P1")
               .antMatchers("/pro/**").hasRole("P2");

        //如果没有权限，跳转到我们自己的无权限提示页面
        http.exceptionHandling().accessDeniedPage("/html/auth.html");

        //如果没有登录，跳转到我们配置自己的登录页面
        http.formLogin()  //启用form登录页
                .loginPage("/html/login.html") //配置我们自己的登录页面
                .loginProcessingUrl("/login") //登录页提交后，登录逻辑处理的url，login是security内部提供好的
                .permitAll();

    }
}
